package com.yeskery.nut.http.sun;

import com.sun.net.httpserver.HttpExchange;
import com.yeskery.nut.core.Method;
import com.yeskery.nut.core.ServerContext;
import com.yeskery.nut.core.ServerRequestConfiguration;
import com.yeskery.nut.core.SessionManager;
import com.yeskery.nut.http.BaseRequest;

import java.io.InputStream;
import java.net.InetSocketAddress;

/**
 * JDK的Http 请求对象
 * @author sprout
 * 2022-05-19 11:08
 */
public class SunRequest extends BaseRequest {

    /** 远程InetSocketAddress对象 */
    private final InetSocketAddress remoteSocketAddress;

    /** 本地InetSocketAddress对象 */
    private final InetSocketAddress localSocketAddress;

    /**
     * 构建一个 {@link SunRequest}
     * @param remoteSocketAddress 远程InetSocketAddress对象
     * @param localSocketAddress 本地InetSocketAddress对象
     * @param serverContext 服务上下文
     * @param sessionManager Session 管理器
     * @param serverRequestConfiguration 服务请求配置对象
     * @param httpExchange Http 交换对象
     * @param inputStream 输入流
     */
    public SunRequest(InetSocketAddress remoteSocketAddress, InetSocketAddress localSocketAddress, ServerContext serverContext,
                      SessionManager sessionManager, ServerRequestConfiguration serverRequestConfiguration, HttpExchange httpExchange, InputStream inputStream) {
        super(serverContext, sessionManager, serverRequestConfiguration);

        this.remoteSocketAddress = remoteSocketAddress;
        this.localSocketAddress = localSocketAddress;
        method = Method.valueOf(httpExchange.getRequestMethod().toUpperCase());
        path = httpExchange.getRequestURI().toASCIIString();
        originalPath = path;
        protocol = httpExchange.getProtocol();
        initUriParameters();

        headers = httpExchange.getRequestHeaders();
        body = readRequestBytesByInputStream(inputStream);
    }

    @Override
    protected byte[] readRequestBytes() {
        return new byte[0];
    }

    @Override
    public String getRemoteAddress() {
        return remoteSocketAddress.getAddress().getHostAddress();
    }

    @Override
    public String getRemoteHost() {
        return remoteSocketAddress.getHostName();
    }

    @Override
    public int getRemotePort() {
        return remoteSocketAddress.getPort();
    }

    @Override
    public String getLocalAddress() {
        return localSocketAddress.getAddress().getHostAddress();
    }

    @Override
    public String getLocalHost() {
        return localSocketAddress.getHostName();
    }

    @Override
    public int getLocalPort() {
        return localSocketAddress.getPort();
    }
}
